﻿using Ldt.CommonCapacitySupport.Business;
using Ldt.CommonCapacitySupport.Business.Model;
using Ldt.DataEngine.LogHandle;
using Ldt.InformationUnit.Common;
using LDT.Task.JudgetDoc.Generation.Model.DataEntity.System;
using LdtDataEngin.ModuleDetail.AnalysisModule.CaseCauseBaseInfoExtr;
using LdtDataEngin.ModuleDetail.AnalysisModule.SituationPlot;
using LdtJudge.DataEngine.CallInterface;
using LdtJudge.DataEngine.CallInterface.ConfigManager;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.CommHelp;
using LdtJudge.DataEngine.Common.StringAssemble;
using LdtJudge.DataEngine.DataBaseStores.Cached;
using LdtJudge.DataEngine.Model.DataModel.CommonManageModel;
using LdtJudge.DataEngine.Model.DataModel.SysCommon;
using LdtJudge.DataEngine.Model.DataModel.SystemtableModel;
using LdtJudge.DataEngine.Model.ElmentModel;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Xml;

namespace Ldt.CommonCapacitySupport.Controllers
{
    /// <summary>
    /// 分析能力提供
    /// </summary>
    [Route("analysiscapacity/v1")]
    [ApiController]
    public class AnalysisCapacityController : Controller
    {
        /// <summary>
        /// 配置对象处理类
        /// </summary>
        private IConfigRetrieval _configRetrieval { get; }
        /// <summary>
        /// http请求对象
        /// </summary>
        private LdtCommonLibraryHttp.HttpHelper _httpHelper { get; }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="configRetrieval">配置中心对象</param>
        /// <param name="httpHelper">http请求对象</param>
        public AnalysisCapacityController(IConfigRetrieval configRetrieval, LdtCommonLibraryHttp.HttpHelper httpHelper)
        {
            _configRetrieval = configRetrieval;
            _httpHelper = httpHelper;
            LoadCommonManageData();

        }
        public static Dictionary<string, object> dicTable = new Dictionary<string, object>();

       /// <summary>
       /// 缓存加载
       /// </summary>
        private void LoadCommonManageData()
        {
            //CacheDataLoade("LdtCommonManage");

            if (dicTable.Count==0)
            {
                IFreeSql ManagefreeSql = LdtJudge.DataEngine.CallInterface.CommHelp.FreeSQLHelp.GetFreeSQL("LdtCommonManage");

                List<ExtractInfo> extractInfoList = ManagefreeSql.Select<ExtractInfo>().ToList();
                dicTable.Add("ExtractInfo", extractInfoList);

                List<ExtractFeature> extractFeatureList = ManagefreeSql.Select<ExtractFeature>().ToList();
                dicTable.Add("ExtractFeature", extractFeatureList);

                List<ElementExtractSource> elementExtractSourceList = ManagefreeSql.Select<ElementExtractSource>().ToList();
                dicTable.Add("ElementExtractSource", elementExtractSourceList);

                List<RuleInfoUnit> ruleInfoUnitList = ManagefreeSql.Select<RuleInfoUnit>().ToList();
                dicTable.Add("RuleInfoUnit", ruleInfoUnitList);

                List<ConvertMode> convertmodeList = ManagefreeSql.Select<ConvertMode>().ToList();
                dicTable.Add("ConvertMode", convertmodeList);

                IFreeSql sysfreeSql = LdtJudge.DataEngine.CallInterface.CommHelp.FreeSQLHelp.GetFreeSQL("Ldt_JudgeDocSystem");
                List<LdtJudge.DataEngine.Model.DataModel.SysCommon.MSYS_Express_Source> express_SourcesList = sysfreeSql.Select<LdtJudge.DataEngine.Model.DataModel.SystemtableModel.SYS_Express_Source, LdtJudge.DataEngine.Model.DataModel.SystemtableModel.SYS_Argument>().InnerJoin((a, b) => a.ES_Purpose == b.AM_ID).ToList<LdtJudge.DataEngine.Model.DataModel.SysCommon.MSYS_Express_Source>();
                string sql = sysfreeSql.Select<LdtJudge.DataEngine.Model.DataModel.SystemtableModel.SYS_Express_Source, LdtJudge.DataEngine.Model.DataModel.SystemtableModel.SYS_Argument>().InnerJoin((a, b) => a.ES_Purpose == b.AM_ID).ToSql();
                dicTable.Add("MSYS_Express_Source", express_SourcesList);

                MsysExpressSourceCached.Initialization(express_SourcesList);
            }


        }
        /// <summary>
        /// 执行设定
        /// </summary>
        /// <param name="outrelatid">唯一ID</param>
        /// <param name="typename">类型名称</param>
        private void SetTaskDataInfo(string outrelatid, string typename)
        {
            //获取日志输出等级配置；
            string loglevel = _configRetrieval.GetAppSettingString("loglevel");
            //进行更新日志平台地址； 
            string logtcp = _configRetrieval.GetAppSettingString("logstash");

            Dictionary<string, string> logConfigDic = new Dictionary<string, string>();
            logConfigDic.Add("varlogstashtcp", logtcp);
            logConfigDic.Add("varloglevel", loglevel);

            LogHandle.GetInitLogHandle.UpdateLogVar(logConfigDic);
            //LogHandle.GetInitLogHandle.UpdateLogVar(new Dictionary<string, string>() { { "varlogstashtcp", logtcp } });
            //if (!string.IsNullOrWhiteSpace(loglevel))
            //    LogHandle.GetInitLogHandle.UpdateLogVar(new Dictionary<string, string>() { { "varloglevel", loglevel } });
            //将日志放入同步数据的文件夹下
            System.Runtime.CallContext.SetData("baseDirectory", _configRetrieval.GetLogPath());
            System.Runtime.CallContext.SetData("typename", typename.ToLower());
            System.Runtime.CallContext.SetData("systemplatform", ConfigManagerHandle.PlatFormName.wordparse_analysisapi);
            System.Runtime.CallContext.SetData("identifier", outrelatid.ToLower());
            System.Runtime.CallContext.SetData("customid", System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());//当前标识ID
        }
        /// <summary>
        /// 卷宗单独分析
        /// </summary>
        /// <param name="anjid">案件ID</param>
        /// <param name="analysisDoc">分析卷宗信息</param>
        /// <returns></returns>
        [HttpPost]
        [Route("analysissourcedoc/{anjid}")]

        public ReturnMessageModel AnalysisSourceDoc(string anjid, [FromBody] AnalysisDocModel analysisDoc, bool fanhuiduanluo = false)
        {
            SetTaskDataInfo(anjid, "analysissourcedoc");
            // 创建计时器
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            ReturnMessageModel returnMessage = new ReturnMessageModel();
            Business.Model.Result res = new Business.Model.Result();
            returnMessage.result = res;
            //returnMessage.body = body;

            LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, "6、调用数据同步接口AnalysisSourceDoc");
            LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, $"6.1 接口接收到的anjid为：{anjid}");
            LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, $"6.2 接口接收到的body数据为：{JsonSerializer.Serialize(analysisDoc)}");
            bodyModel resultcontent = new bodyModel() ;
            try
            {
                AnalysisCapacity_Business analysisCapacity_Business = new AnalysisCapacity_Business(_configRetrieval);
                //进行分析文书
                resultcontent = analysisCapacity_Business.AnalysisSourceDoc(anjid, analysisDoc,fanhuiduanluo,dicTable);

                if (resultcontent!=null)
                {
                    returnMessage.body = resultcontent;
                    res.message = "数据存储完成！";
                    res.code = "1";
                    LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, $"6.3.1 数据保存完成！");
                }
                else
                {
                    res.message = "数据转换失败！";
                    res.code = "0";
                    LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, $"6.3.2 数据转换失败！");
                }
            }
            catch (Exception ex)
            {
                res.message = "数据转换失败！"+ ex.ToString();
                res.code = "0";
                LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Error, $"6.3.2 进行数据分析时失败！" + System.Environment.NewLine + "进行数据分析时失败，详细消息为：" + ex.ToString());
            }

            if (!string.IsNullOrWhiteSpace(analysisDoc.BackUrl))
            {
                ReturnMessageModel returnMessaget = new ReturnMessageModel();
                Result rest = new Result();
                returnMessaget.result = rest;
                if (res.code == "0")
                {
                    rest.message = res.message;
                    rest.code = res.code;
                    LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Error, "在文书分析时，出现错误，所以不进行数据转换！");
                }
                else
                {
                    try
                    {
                        //获取DOC库中优选后的数据
                        rest.message = "数据转换成功！";
                        rest.code = "1";
                        returnMessaget.body = resultcontent;
                    }
                    catch (Exception ex)
                    {
                        rest.message = "数据转换失败！";
                        rest.code = "0";
                        LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Error, "进行数据推送，推送后的获取到的结果为：" + ex.ToString());
                    }
                }

                string datastr = JsonSerializer.Serialize(returnMessaget);
                try
                {
                    string result = _httpHelper.PostAsync(analysisDoc.BackUrl, datastr).Result.StatusCode.ToString();
                    LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, $"进行数据推送地址为{analysisDoc.BackUrl}，推送接口的状态为：" + result);
                }
                catch (Exception)
                {
                    LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, $"推送失败！！！！进行数据推送地址为{analysisDoc.BackUrl}，推送接口的状态为：");
                }
            }

            stopwatch.Stop();
            //returnMessage.body = stopwatch.Elapsed.TotalMilliseconds.ToString("0");
            return returnMessage;
        }

        /// <summary>
        /// 根据卷宗内容匹配争议焦点
        /// </summary>
        /// <param name="anjid">案件ID</param>
        /// <param name="analysisDoc">卷宗对象</param>
        /// <returns></returns>
        [HttpPost]
        [Route("analysisdossierparagraph/{anjid}")]
        public ReturnMessageModel AnalysisDossierParagraph(string anjid, [FromBody] AnalysisDocModel analysisDoc)
        {
            SetTaskDataInfo(anjid, "analysisdossierparagraph");

            ReturnMessageModel returnMessage = new ReturnMessageModel();
            dynamic dynamicBody = new System.Dynamic.ExpandoObject();
            Result res = new Result();
            returnMessage.result = res;
            returnMessage.body = dynamicBody;
            dynamicBody.OutRealtID = anjid;
            dynamicBody.CaseID = "";
            dynamicBody.CaseCode = "";

            LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, "调用数据同步接口AnalysisDossierParagraph");
            LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, $"接口接收到的anjid为：{anjid}");
            LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, $"接口接收到的body数据为：{JsonSerializer.Serialize(analysisDoc)}");

            try
            {
                //进行分析文书
                AnalysisCapacity_Business analysisCapacity_Business = new AnalysisCapacity_Business(_configRetrieval);
                //进行分析文书
                var dicparlist = analysisCapacity_Business.AnalysisDossierParagraph(anjid, analysisDoc);
                if (dicparlist != null)
                {
                    if (dicparlist.Any(a => a.Key.ToLower() == "ms_cr_defendantsuggest"))
                    {//判断存在被告答辩
                        string message = "";
                        var defsuggest = dicparlist.FirstOrDefault(code => code.Key.ToLower() == "ms_cr_defendantsuggest");
                        IDictionary<string, string> argumelist = analysisCapacity_Business.MatchArgument(string.Join("\n", defsuggest.Value), analysisDoc.Anyid, "RecordProduction", "AnswerOpinion", out message);
                        if (argumelist != null && argumelist.Count > 0)
                        {
                            //如果匹配到的争议焦点数量大于0，则表示匹配到了内容
                            List<dynamic> argumentlist = new List<dynamic>();
                            foreach (var keyValuePair in argumelist)
                            {
                                argumentlist.Add(new { ArgumentCode = keyValuePair.Key, ArgumentExpress = keyValuePair.Value });
                            }

                            dynamicBody.ResultArgumentFocus = argumentlist.ToArray();
                            res.message = message;
                            res.code = "1";
                            LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, "接口返回数据为：" + JsonSerializer.Serialize(returnMessage));
                        }
                        else
                        {
                            res.message = "匹配争议焦点完成，但没有匹配到争议焦点";
                            res.code = "0";
                            LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, res.message + " @@ " + message);
                        }
                    }
                    else
                    {
                        res.message = "文书分段完成，但不存在被告答辩逻辑段！";
                        res.code = "0";
                        LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, $" 文书分段完成，但不存在被告答辩逻辑段！");
                    }
                }
                else
                {
                    res.message = "文书分段失败！";
                    res.code = "0";
                    LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, $" 文书分段失败！");
                }
            }
            catch (Exception ex)
            {
                res.message = "文书分段失败或获取争议焦点失败！";
                res.code = "0";
                LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Error, $" 文书分段失败或获取争议焦点失败！");
                LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Error, "文书分段失败或获取争议焦点失败，详细消息为：" + ex.ToString());
            }
            return returnMessage;



        }

        /// <summary>
        /// 案由要素转换
        /// </summary>
        /// <param name="converDictionaryModel"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("convertdictionarybyxml")]
        public ReturnMessageModel ConvertdictionaryByXml([FromBody] ConverDictionaryModel converDictionaryModel)
        {
            Dictionary<string, ElementConfigModel> dickeyvalues = new Dictionary<string, ElementConfigModel>();
            string errmessage = "";
            GetSysCaseCause dalCause = new GetSysCaseCause();
            ReturnMessageModel returnMessageModel = new ReturnMessageModel();
            IFreeSql freeSql = LdtJudge.DataEngine.CallInterface.CommHelp.FreeSQLHelp.GetFreeSQL("Ldt_JudgeDocSystem");
            if (!string.IsNullOrEmpty(converDictionaryModel.CauseID) && !string.IsNullOrEmpty(converDictionaryModel.CaseType))
            {
                try
                {
                    #region 加载配置信息
                    CaseCauseModel cause = dalCause.GetModelByCauseName(converDictionaryModel.CauseID, converDictionaryModel.CaseType);
                    if (!string.IsNullOrWhiteSpace(cause.ConfigXML))
                    {
                        XmlDocument oDom = new XmlDocument();
                        oDom.LoadXml(cause.ConfigXML);

                        List<SYS_ArgumentType> oTb = dalCause.GetArgumentTypeByAt_CauseID(converDictionaryModel.CauseID);
                        XmlNodeList list = oDom.SelectNodes("/elementConfig/element");
                        foreach (XmlNode oNode in list)
                        {
                            ElementConfigModel newconfig = new ElementConfigModel();

                            #region 新属性值加载

                            newconfig.isNodeByAtticton = "1";
                            foreach (XmlNode node in oNode.ChildNodes)
                            {
                                if (!newconfig.DictionaryAttribute.ContainsKey(node.Name))
                                {
                                    newconfig.DictionaryAttribute.Add(node.Name, node.Value ?? "");
                                }
                            }

                            #endregion


                            string xmlPath = oNode.Attributes["xmlPath"].Value;
                            xmlPath = Regex.Replace(xmlPath, "^(?!/)", "/");        //假如配置的路径不包含开始符"/"时，则追加上。

                            newconfig.XmlPath = xmlPath;

                            XmlNode AttributeNode = oNode.SelectSingleNode("checkType"); //单行提取
                            newconfig.checkType = (AttributeNode == null) ? "radio" : AttributeNode.InnerText;

                            AttributeNode = oNode.SelectSingleNode("sourceType");//数据源类型
                            newconfig.sourceType = (AttributeNode == null) ? "" : AttributeNode.InnerText;

                            AttributeNode = oNode.SelectSingleNode("defaultValue");//默认值
                            newconfig.defaultValue = (AttributeNode == null) ? "" : AttributeNode.InnerText;

                            AttributeNode = oNode.SelectSingleNode("isSerialField");//
                            newconfig.isSerialField = (AttributeNode == null) ? 0 : LdFormat.ObjectToInt(AttributeNode.InnerText);

                            AttributeNode = oNode.SelectSingleNode("fieldType");//字段类型
                            newconfig.fieldType = (AttributeNode == null) ? "varchar" : AttributeNode.InnerText;

                            AttributeNode = oNode.SelectSingleNode("formatType");//是否格式化
                            if (AttributeNode != null)
                            {
                                newconfig.formatType = (AttributeNode == null) ? "" : AttributeNode.InnerText;
                            }


                            AttributeNode = oNode.SelectSingleNode("suitDegreeID");//诉讼地位
                            newconfig.suitDegreeID = (AttributeNode == null) ? "" : LdFormat.ObjectToString(AttributeNode.InnerText);

                            AttributeNode = oNode.SelectSingleNode("matchPersonMode");//人员信息匹配
                            newconfig.matchPersonMode = (AttributeNode == null) ? "" : LdFormat.ObjectToString(AttributeNode.InnerText);

                            AttributeNode = oNode.SelectSingleNode("matchPersonCondi");//人员匹配类型
                            newconfig.matchPersonCondi = (AttributeNode == null) ? "" : LdFormat.ObjectToString(AttributeNode.InnerText);

                            AttributeNode = oNode.SelectSingleNode("isAloneExtract");//自定义提取
                            newconfig.isAloneExtract = (AttributeNode == null) ? 0 : LdFormat.ObjectToInt(AttributeNode.InnerText);

                            AttributeNode = oNode.SelectSingleNode("isMultiExact");//多行
                            newconfig.isMultiExact = (AttributeNode == null) ? 0 : LdFormat.ObjectToInt(AttributeNode.InnerText);

                            AttributeNode = oNode.SelectSingleNode("sourceContent");//
                            string sourceArgument = (AttributeNode == null) ? "" : LdFormat.ObjectToString(AttributeNode.InnerText);
                            if (AttributeNode != null && !string.IsNullOrWhiteSpace(AttributeNode.InnerText))
                            {
                                var dataRows = oTb.Where(a => a.AT_Code == sourceArgument);
                                if (dataRows != null && dataRows.Count() > 0)
                                {
                                    newconfig.sourceContent = sourceArgument;
                                }
                            }

                            if (!dickeyvalues.ContainsKey(xmlPath))
                            {
                                if (newconfig.sourceType == "paramter")
                                {
                                    dickeyvalues.Add(xmlPath, newconfig);
                                }

                            }

                        }

                        //添加对要素结点的配置
                        XmlNodeList nodelist = oDom.SelectNodes("/elementConfig/node");
                        foreach (XmlNode oNode in nodelist)
                        {
                            ElementConfigModel cnodeDefine = new ElementConfigModel();

                            #region 新属性值添加

                            cnodeDefine.isNodeByAtticton = "0";
                            foreach (XmlNode node in oNode.ChildNodes)
                            {
                                if (!cnodeDefine.DictionaryAttribute.ContainsKey(node.Name))
                                {
                                    cnodeDefine.DictionaryAttribute.Add(node.Name, node.Value);
                                }

                            }

                            #endregion

                            string xmlPath = oNode.Attributes["xmlPath"].Value;
                            xmlPath = Regex.Replace(xmlPath, "^(?!/)", "/");        //假如配置的路径不包含开始符"/"时，则追加上。
                            cnodeDefine.XmlPath = xmlPath;

                            XmlNode nAttrNode = oNode.SelectSingleNode("isPersonNode");
                            cnodeDefine.isPersonNode = (nAttrNode == null) ? 0 : LdFormat.ObjectToInt(nAttrNode.InnerText);

                            nAttrNode = oNode.SelectSingleNode("suitDegreeID");
                            cnodeDefine.suitDegreeID = (nAttrNode == null) ? "" : LdFormat.ObjectToString(nAttrNode.InnerText);

                            nAttrNode = oNode.SelectSingleNode("matchPersonMode");
                            cnodeDefine.matchPersonMode = (nAttrNode == null) ? "" : LdFormat.ObjectToString(nAttrNode.InnerText);

                            nAttrNode = oNode.SelectSingleNode("matchPersonCondi");
                            cnodeDefine.matchPersonCondi = (nAttrNode == null) ? "" : LdFormat.ObjectToString(nAttrNode.InnerText);

                            nAttrNode = oNode.SelectSingleNode("isAloneExtract");
                            cnodeDefine.isAloneExtract = (nAttrNode == null) ? 0 : LdFormat.ObjectToInt(nAttrNode.InnerText);

                            nAttrNode = oNode.SelectSingleNode("isMultiExact");
                            cnodeDefine.isMultiExact = (nAttrNode == null) ? 0 : LdFormat.ObjectToInt(nAttrNode.InnerText);

                            nAttrNode = oNode.SelectSingleNode("parentnode");
                            cnodeDefine.parentnode = (nAttrNode == null) ? "" : LdFormat.ObjectToString(nAttrNode.InnerText);

                            XmlNode AttributeNode = oNode.SelectSingleNode("checkType"); //单行提取
                            cnodeDefine.checkType = (AttributeNode == null) ? "radio" : AttributeNode.InnerText;

                            //2016-11-24 fyb 用于推原告
                            nAttrNode = oNode.SelectSingleNode("plaintiff");
                            cnodeDefine.plainTiff = (nAttrNode == null) ? 0 : LdFormat.ObjectToInt(nAttrNode.InnerText);
                            if (!dickeyvalues.ContainsKey(xmlPath))
                            {
                                if (cnodeDefine.sourceType == "paramter")
                                {
                                    dickeyvalues.Add(xmlPath, cnodeDefine);
                                }

                            }

                        }
                    }
                    #endregion

                    byte[] filestream = Convert.FromBase64String(converDictionaryModel.Xmldoc);
                    string sourceContent = Encoding.Default.GetString(filestream);
                    XmlDocument xmlDocument = new XmlDocument();
                    xmlDocument.LoadXml(sourceContent);
                    foreach (var dic in dickeyvalues)
                    {
                        string xmlpath = dic.Key.Split('@')[0];
                        xmlpath = xmlpath.Replace("/案由要素/", "案由要素/");
                        xmlpath = xmlpath.Substring(0, xmlpath.Length - 1);
                        string name = dic.Key.Split('@')[1];
                        XmlNodeList xmlNodeList = xmlDocument.SelectNodes(xmlpath);
                        if (xmlNodeList.Count > 0 && xmlNodeList != null)
                        {
                            foreach (XmlNode node in xmlNodeList)
                            {
                                if (node.Attributes[name] != null && node.Attributes[name].Value != null)
                                {
                                    string value = node.Attributes[name].Value;
                                   
                                    string txtvalue = "";
                                    if (value.IndexOf(",")>-1)
                                    {
                                        foreach (string item in value.Split(','))
                                        {
                                            List<LdtJudge.DataEngine.Model.DataModel.SysCommon.SYS_Argument> sYS_ArgumentList = freeSql.Select<SYS_ArgumentType, LdtJudge.DataEngine.Model.DataModel.SysCommon.SYS_Argument>().LeftJoin((a, b) => a.AT_ID == b.AT_ID).Where((a, b) => a.AT_Code == dic.Value.sourceContent && b.AM_Code == item)?.ToList((a, b) => new LdtJudge.DataEngine.Model.DataModel.SysCommon.SYS_Argument { AM_Code = b.AM_Code, AM_Name = b.AM_Name });
                                            if (sYS_ArgumentList.Count > 0)
                                            {
                                                if (txtvalue=="")
                                                {
                                                    txtvalue = sYS_ArgumentList[0].AM_Name;
                                                }
                                                else
                                                {
                                                    txtvalue = txtvalue+","+ sYS_ArgumentList[0].AM_Name;
                                                }
                                                
                                            }
                                        }
                                    }
                                    else
                                    {
                                        List<LdtJudge.DataEngine.Model.DataModel.SysCommon.SYS_Argument> sYS_ArgumentList = freeSql.Select<SYS_ArgumentType, LdtJudge.DataEngine.Model.DataModel.SysCommon.SYS_Argument>().LeftJoin((a, b) => a.AT_ID == b.AT_ID).Where((a, b) => a.AT_Code == dic.Value.sourceContent && b.AM_Code == value)?.ToList((a, b) => new LdtJudge.DataEngine.Model.DataModel.SysCommon.SYS_Argument { AM_Code = b.AM_Code, AM_Name = b.AM_Name });
                                        if (sYS_ArgumentList.Count > 0)
                                        {
                                            txtvalue = sYS_ArgumentList[0].AM_Name;
                                        }
                                    }
                                    if (!string.IsNullOrEmpty(txtvalue))
                                    {
                                        node.Attributes[name].Value = txtvalue;
                                    }
                                   
                                }
                            }
                        }
                    }
                    Result result = new Result();
                    result.code = "1";
                    result.message = "转换完毕";
                    returnMessageModel.result = result;
                    returnMessageModel.body =HttpHelp.EnDataBase64(xmlDocument.OuterXml);
                }
                catch (Exception ex)
                {
                    Result result = new Result();
                    result.code = "0";
                    result.message = "转换失败"+ex.ToString() ;
                    returnMessageModel.result = result;
                }
            }
            else
            {
                Result result = new Result();
                result.code = "0";
                result.message = "转换失败，案件类型与案由ID错误";
                returnMessageModel.result = result;
            }

            return returnMessageModel;
        }


        /// <summary>
        /// 进行对争议焦点处理
        /// </summary>
        /// <param name="anjid">案件的唯一ID</param>
        /// <param name="focusModelRoot">争议焦点处理对象内容</param>
        /// <returns></returns>
        [HttpPost]
        [Route("handleargumentfocus/{anjid}")]
        public ReturnMessageModel HandleArgumentFocus(string anjid, [FromBody] AnalysisAPIModel focusModelRoot)
        {
            SetTaskDataInfo(anjid, "HandleArgumentFocus");
            ReturnMessageModel returnMessage = new ReturnMessageModel();
            dynamic dynamicBody = new System.Dynamic.ExpandoObject();
            Result res = new Result();
            returnMessage.result = res;
            returnMessage.body = dynamicBody;


            LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, "B、调用数据同步业务分析接口HandleArgumentFocus");
            LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, $"B.1 接口接收到的唯一ID为：{anjid}");
            LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, $"B.2 接口接收到的body数据为：{JsonSerializer.Serialize(focusModelRoot)}");

            AnalysisCapacity_Business analysisCapacity_Business = new AnalysisCapacity_Business(_configRetrieval);

            if (focusModelRoot == null)
            {
                WriteMessage(ref dynamicBody, ref res, "数据传入的对象无法转换");
                return returnMessage;
            }

            if (focusModelRoot.ParagraphModelsList == null || focusModelRoot.ParagraphModelsList.Count <= 0)
            {
                WriteMessage(ref dynamicBody, ref res, "数据传入的对象争议焦点段落内容为空！");
                return returnMessage;
            }

            if (!focusModelRoot.ParagraphModelsList.Any(code => code.Paragraphcode.ToLower() == "ms_cr_defendantsuggest") && !focusModelRoot.ParagraphModelsList.Any(code => code.Paragraphcode.ToLower() == "ms_im_litigation request"))
            {
                //WriteMessage(ref dynamicBody, ref res, "数据传入的对象不包含被告答辩的段落！");
                WriteMessage(ref dynamicBody, ref res, "数据传入的对象不包含被告答辩或者诉请的段落！");
                return returnMessage;
            }

            if (string.IsNullOrWhiteSpace(focusModelRoot.Anyid))
            {
                WriteMessage(ref dynamicBody, ref res, "数据传入的对象案由ID为空！");
                return returnMessage;
            }

            string message = "";
            IDictionary<string, string> argumelist;
            if (focusModelRoot.Juanzbh.Contains("MSSuitBook"))
            {
                //如果是诉状，
                argumelist = analysisCapacity_Business.MatchArgument(focusModelRoot.ParagraphModelsList[0].ParagraphText, focusModelRoot.Anyid, "MSSuitBook", "MS_IM_Litigation Request", out message);
            }
            else
            {
                //如果是笔录
                argumelist = analysisCapacity_Business.MatchArgument(focusModelRoot.ParagraphModelsList[0].ParagraphText, focusModelRoot.Anyid, "RecordProduction", "AnswerOpinion", out message);
            }
            if (argumelist != null && argumelist.Count > 0)
            {
                //如果匹配到的争议焦点数量大于0，则表示匹配到了内容
                List<dynamic> argumentlist = new List<dynamic>();
                foreach (var keyValuePair in argumelist)
                {
                    argumentlist.Add(new { ArgumentCode = keyValuePair.Key, ArgumentExpress = keyValuePair.Value });
                }

                dynamicBody.ResultArgumentFocus = argumentlist.ToArray();
                res.message = message;
                res.code = "1";
                LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, "B.3接口返回数据为：" + JsonSerializer.Serialize(returnMessage));
                return returnMessage;
            }
            else
            {
                WriteMessage(ref dynamicBody, ref res, message);
                return returnMessage;
            }
        }

        /// <summary>
        /// 案件要素优选能力
        /// </summary>
        /// <param name="analysisAPIModel"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("optimizationelement")]
        public ReturnMessageModel OptimizationElement([FromBody] AnalysisApiElement analysisApiElement)
        {
            SetTaskDataInfo("", "optimizationelement");
            ReturnMessageModel returnMessage = new ReturnMessageModel();
            Business.Model.Result res = new Business.Model.Result();
            returnMessage.result = res;
            LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, "6、调用数据同步接口optimizationelement");
            LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, $"6.2 接口接收到的body数据为：{JsonSerializer.Serialize(analysisApiElement)}");
            bodyModel resultcontent = new bodyModel();
            try
            {
                AnalysisCapacity_Business analysisCapacity_Business = new AnalysisCapacity_Business(_configRetrieval);
                //进行分析文书
                resultcontent = analysisCapacity_Business.AnalysisSourceDocElment(analysisApiElement);

                if (resultcontent != null)
                {
                    returnMessage.body = resultcontent;
                    res.message = "数据存储完成！";
                    res.code = "1";
                    LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, $"6.3.1 数据保存完成！");
                }
                else
                {
                    res.message = "数据转换失败！";
                    res.code = "0";
                    LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, $"6.3.2 数据转换失败！");
                }
            }
            catch (Exception ex)
            {
                res.message = "数据转换失败！" + ex.ToString();
                res.code = "0";
                LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Error, $"6.3.2 进行数据分析时失败！" + System.Environment.NewLine + "进行数据分析时失败，详细消息为：" + ex.ToString());
            }
            if (!string.IsNullOrWhiteSpace(analysisApiElement.backurl))
            {
                ReturnMessageModel returnMessaget = new ReturnMessageModel();
                Result rest = new Result();
                returnMessaget.result = rest;
                if (res.code == "0")
                {
                    rest.message = res.message;
                    rest.code = res.code;
                    LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Error, "在文书分析时，出现错误，所以不进行数据转换！");
                }
                else
                {
                    try
                    {
                        //获取DOC库中优选后的数据
                        rest.message = "数据转换成功！";
                        rest.code = "1";
                    }
                    catch (Exception ex)
                    {
                        rest.message = "数据转换失败！";
                        rest.code = "0";
                        LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Error, "进行数据推送，推送后的获取到的结果为：" + ex.ToString());
                    }
                }

                string datastr = JsonSerializer.Serialize(returnMessaget);
                try
                {
                    string result = _httpHelper.PostAsync(analysisApiElement.backurl, datastr).Result.StatusCode.ToString();
                    LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, $"进行数据推送地址为{analysisApiElement.backurl}，推送接口的状态为：" + result);
                }
                catch (Exception)
                {
                    LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, $"推送失败！！！！进行数据推送地址为{analysisApiElement.backurl}，推送接口的状态为：");
                }
            }
            return returnMessage;
        }

        /// <summary>
        /// 违法行为提取
        /// </summary>
        /// <param name="offenceElement"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("offenceelement")]
        public ReturnMessageModel OffenceElement([FromBody] OffenceElement offenceElement)
        {
            ReturnMessageModel returnMessage = new ReturnMessageModel();
            Business.Model.Result res = new Business.Model.Result();
            returnMessage.result = res;
            try
            {
                Dictionary<string, string> dicElement = new Dictionary<string, string>();
                dicElement.Add("fileFullName", @"config\moduleconfig\commonconfig\generalconfig\causeextract\causeextract.xmlldt");
                string elementMessage = WebUtil.DoGet(_configRetrieval.GetAppSettingString("systemapi") + "/api/WordParse/GetConfigFileContent", dicElement, "utf-8");

                CaseCauseExtract caseCauseExtract = new CaseCauseExtract(null,null);
                List<CaseCauseModel> caseCauseModels= caseCauseExtract.GetCausesByMachineLearn(offenceElement.ParagraphText);

                AnalysisCapacity_Business capacity_Business = new AnalysisCapacity_Business(_configRetrieval);
                if (string.IsNullOrEmpty(offenceElement.District))
                {
                    offenceElement.District = _configRetrieval.GetAppSettingString("district");
                }
                returnMessage.body = capacity_Business.OffenceElementClass(offenceElement, caseCauseModels);
                res.message = "提取成功！";
                res.code = "1";
            }
            catch (Exception ex)
            {

                res.message = "提取失败！" + ex.ToString();
                res.code = "1";
            }
           
            return returnMessage;
        }

        /// <summary>
        /// 情形情节提取接口
        /// </summary>
        /// <param name="plotExtractModel"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("situationandplotextract")]
        public ReturnMessageModel SituationandPlotExtract([FromBody] PlotExtractModel plotExtractModel) 
        {
            SetTaskDataInfo("", "situationandplotextract");
            // 创建计时器
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            ReturnMessageModel returnMessage = new ReturnMessageModel();
            Business.Model.Result res = new Business.Model.Result();
            returnMessage.result = res;
            //returnMessage.body = body;

            LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, "6、调用数据同步接口situationandplotextract");
            LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, $"6.2 接口接收到的body数据为：{System.Text.Json.JsonSerializer.Serialize(plotExtractModel)}");

            try
            {
                Dictionary<string, string> dicElement = new Dictionary<string, string>();
                dicElement.Add("fileFullName", @"config\moduleconfig\commonconfig/generalconfig\qxqjconfig\qxqjcaseworking_struct.xml");
                string elementMessage = WebUtil.DoGet(_configRetrieval.GetAppSettingString("systemapi") + "/api/WordParse/GetConfigFileContent", dicElement, "utf-8");
                dicElement = new Dictionary<string, string>();
                dicElement.Add("fileFullName", @"config\moduleconfig\commonconfig\generalconfig\qxqjmatchlearnconfig\qxqj_machinelearning.xml");
                string Message = WebUtil.DoGet(_configRetrieval.GetAppSettingString("systemapi") + "/api/WordParse/GetConfigFileContent", dicElement, "utf-8");
                dynamic elementcofig = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(elementMessage);
                string configContent = "";
                if (elementcofig.result.code.ToString() == "1")
                    configContent = elementcofig.body;
                string configContentML = "";
                dynamic elementcofigML = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(Message);
                if (elementcofigML.result.code.ToString() == "1")
                    configContentML = elementcofigML.body;

                List<Dictionary<string, string>> dicList = new List<Dictionary<string, string>>();
                foreach (var paragrap in plotExtractModel.Paragraph)
                {
                    paragrap.Content = HttpHelp.DeCodeBase64new(65001, paragrap.Content);
                    if (paragrap.IsPlot.IndexOf("0") > -1)
                    {
                        ExtSituationData extSituationData = new ExtSituationData(configContentML);
                        List<Dictionary<string, string>> value = extSituationData.MatchSituationSupplementSuperr(paragrap.Code, paragrap.Content, plotExtractModel.CaseType, plotExtractModel.docType, plotExtractModel.CaseCause, configContent, "2");
                        if (value.Count > 0)
                        {
                            foreach (Dictionary<string, string> dic in value)
                            {
                                Dictionary<string, string> dicvalue = new Dictionary<string, string>();
                                dicvalue.Add("affirmidearesult", dic["rs_affirmidearesult"]);
                                dicvalue.Add("name", dic["rs_situationname"]);
                                dicvalue.Add("source", dic["rs_statussource"]);
                                dicvalue.Add("rs_situationid", dic["rs_situationid"]);
                                dicvalue.Add("originaltext", dic["originaltext"]);
                                dicvalue.Add("ew_id", dic["ew_id"]);
                                dicvalue.Add("IsPlot", "0");
                                dicvalue.Add("CaseCause", dic["CaseCause"]);
                                dicList.Add(dicvalue);
                            }
                        }
                    }
                    if (paragrap.IsPlot.IndexOf("1") > -1)
                    {
                        ExtPlotData extPlotData = new ExtPlotData(configContentML);
                        List<Dictionary<string, string>> value = extPlotData.MatchSituationSupplementSuperr(paragrap.Code, paragrap.Content, plotExtractModel.CaseType, plotExtractModel.docType, plotExtractModel.CaseCause, configContent);
                        foreach (Dictionary<string, string> dic in value)
                        {
                            Dictionary<string, string> dicvalue = new Dictionary<string, string>();
                            dicvalue.Add("affirmidearesult", dic["po_affirmidearesult"]);
                            dicvalue.Add("name", dic["po_plotname"]);
                            dicvalue.Add("source", dic["po_plotsource"]);
                            dicvalue.Add("rs_situationid", dic["po_plotid"]);
                            dicvalue.Add("originaltext", dic["originaltext"]);
                            dicvalue.Add("ew_id", "");
                            dicvalue.Add("IsPlot", "1");
                            dicvalue.Add("CaseCause", dic["CaseCause"]);
                            dicList.Add(dicvalue);
                        }
                    }

                }
                returnMessage.body = dicList;
                res.message = "提取成功！";
                res.code = "1";
            }
            catch (Exception ex)
            {

                res.message = "提取失败！" + ex.ToString(); ;
                res.code = "1";
            }
           
            return returnMessage;
        }

        /// <summary>
        /// 传入段落数据分析
        /// </summary>
        /// <param name="paragraphModel">段落数据</param>
        [HttpPost]
        [Route("paragraphanalysissourcedoc")]
        public ReturnMessageModel ParagraphAnalysisSourceDoc([FromBody] AnalysisParagraphModel paragraphModel)
        {
            SetTaskDataInfo("", "paragraphanalysissourcedoc");
            ReturnMessageModel returnMessage = new ReturnMessageModel();
            Business.Model.Result res = new Business.Model.Result();
            LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, "调用数据同步接口ParagraphAnalysisSourceDoc");
            LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, $"接口接收到的body数据为：{JsonSerializer.Serialize(paragraphModel)}");
            bodyModel resultcontent = new bodyModel();
            try
            {
                AnalysisCapacity_Business analysisCapacity_Business = new AnalysisCapacity_Business(_configRetrieval);
                //进行分析文书
                resultcontent = analysisCapacity_Business.AnalysisParagraph(paragraphModel);
                if (resultcontent != null)
                {
                    returnMessage.body = resultcontent;
                    res.message = "段落数据分析完成！";
                    res.code = "1";
                    LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, $"段落数据分析完成！");
                }
                else
                {
                    res.message = "段落数据分析失败！";
                    res.code = "0";
                    LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, $"段落数据分析失败！");
                }
            }
            catch (Exception ex)
            {
                res.message = "段落数据分析失败！" + ex.ToString();
                res.code = "0";
                LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Error, $"段落数据分析失败！" + System.Environment.NewLine + "进行数据分析时失败，详细消息为：" + ex.ToString());
            }
            returnMessage.result = res;
            return returnMessage;
        }

        /// <summary>
        /// 处理消息的输出
        /// </summary>
        /// <param name="body">写入消息</param>
        /// <param name="res">返回结果</param>
        /// <param name="messagetext">消息内容</param>
        private void WriteMessage(ref dynamic body, ref Result res, string messagetext)
        {
            body.CaseID = "";
            body.OutRealtID = "";
            res.message = messagetext;
            res.code = "0";
            LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, messagetext);
        }


    }
}
